﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI_Demo.Filter
{
    //全局异常过滤器
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<GlobalExceptionFilter> _logger;
        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            _logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            //获取出问题的方法
            var operation = context.HttpContext.Request.RouteValues["controller"] + "/" + context.HttpContext.Request.RouteValues["action"];

            //记录下错误
            _logger.LogError(context.Exception, $"{operation}  Exception:" + context.Exception.Message); //记录错误日志
                                                                                                         //拦截处理
            //如果        
            if (!context.ExceptionHandled)
            {
                context.Result = new JsonResult(new
                {
                    status = false,
                    msg = "系统内部错误:" + context.Exception.Message
                });
                context.ExceptionHandled = true;
            }
        }
    }
   /* public class GlobalExceptionFilter : IExceptionFilter
    {
        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            Exception ex = context.Exception;
            string errMsg = "GlobalExceptionFilter-OnException：" + ex.Message;
            //记录获取到的异常信息
        }
    }*/
}